/**
 * 
 */
package com.cloud.advice;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 	统一返回值格式处理
 */

@Component
public class ResponseBodyHandlerWrapperInit implements InitializingBean {

	@Autowired
	private RequestMappingHandlerAdapter adapter;

	@Override
	public void afterPropertiesSet() throws Exception {
		List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter
				.getReturnValueHandlers();
		List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(
				returnValueHandlers);
		decorateHandlers(handlers);
		adapter.setReturnValueHandlers(handlers);
	}

	/**
	 * 处理RequestResponseBodyMethodProcessor，使用自定义ResponseBodyWrapperHandler
	 * 处理返回对象
	 * @param handlers
	 */
	private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
		for (HandlerMethodReturnValueHandler handler : handlers) {
			if (handler instanceof RequestResponseBodyMethodProcessor) {
				// 用自己的ResponseBody包装类替换掉框架的，达到返回Result的效果
				ResponseBodyWrapperHandler decorator = new ResponseBodyWrapperHandler(handler);
				int index = handlers.indexOf(handler);
				handlers.set(index, decorator);
				break;
			}
		}
	}
}
